package com.hmall.common.config;

import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.lang.reflect.Type;

/**
 * RabbitMQ 配置
 *
 * @author Moozy
 * @since 2025/5/4
 **/
@Configuration
public class MqConfig {

    @Bean
    MessageConverter messageConverter() {
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter() {
            @Override
            protected Message createMessage(Object objectToConvert, MessageProperties messageProperties, Type genericType) throws MessageConversionException {
                Long userId = UserContext.getUser();
                if (userId != null) {
                    messageProperties.setHeader("user-info", userId);
                }
                return super.createMessage(objectToConvert, messageProperties, genericType);
            }

            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                Long userId = message.getMessageProperties().getHeader("user-info");
                if (userId != null) {
                    UserContext.setUser(userId);
                }
                return super.fromMessage(message);
            }
        };
        // 配置自动创建消息 ID，识别不同消息
        converter.setCreateMessageIds(true);
        return converter;
    }
    
}
